package leetcode.code1366;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Solution {
	public String rankTeams(String[] votes) {
		Character[] teams = new Character[votes[0].length()];
		for (int i = 0; i < votes[0].length(); i++) {
			teams[i] = votes[0].charAt(i);
		}
		Map<Character, Integer> idx = new HashMap<>();
		for (int i = 0; i < teams.length; i++) {
			idx.put(teams[i], i);
		}
		int size = teams.length;
		int[][] v = new int[size][size];
		for (int i = 0; i < votes.length; i++) {
			for (int j = 0; j < v[0].length; j++) {
				char c = votes[i].charAt(j);
				v[idx.get(c)][j]++;
			}
		}
		Arrays.sort(teams, (a, b) -> {
			int[] idx1 = v[idx.get(a)];
			int[] idx2 = v[idx.get(b)];
			for (int i = 0; i < size; i++) {
				if (idx1[i] != idx2[i]) {
					return idx2[i] - idx1[i];
				}
			}
			return a - b;
		});
		StringBuffer ans = new StringBuffer();
		for (int i = 0; i < votes[0].length(); i++) {
			ans.append(teams[i]);
		}
		return ans.toString();
	}
}
